package com.example.imtoken.modules.private_import

import com.example.imtoken.R
import com.example.imtoken.core.base.BaseActivity
import com.example.imtoken.databinding.ActivityPrivateImportCodeBinding
import com.example.imtoken.modules.private_import.fragment.code.CodeFragment
import com.example.imtoken.modules.private_import.fragment.plaintext.PlaintextFragment
import com.xuexiang.xui.adapter.FragmentAdapter

class PrivateImportCodeActivity :
    BaseActivity<PrivateImportCodeViewModel, ActivityPrivateImportCodeBinding>(
        PrivateImportCodeViewModel::class.java
    ) {

    private val importType by lazy {
        intent.getIntExtra("importType", 0)
    }

    private val titles = arrayOfNulls<String>(2)

    private val fragments = arrayListOf(
        PlaintextFragment(),
        CodeFragment()
    )

    private val passWord by lazy {
        intent.getStringExtra("passWord")
    }

    override fun initLayoutId(): Int {
        return R.layout.activity_private_import_code
    }

    override fun init() {
        when (importType) {
            1 -> {
                titles[0] = getString(R.string.keyStore)
                viewModel.getKeyStoreData(passWord)
            }
            2 -> {
                titles[0] = getString(R.string.privateKey)
                viewModel.getPrivateKeyData(passWord)
            }
        }
        titles[1] = getString(R.string.QrCode)
        initView()
        initTitle()
        initClick()
        initObserve()
    }

    private fun initObserve() {
        viewModel.getKeyStoreData().observe(this) {
            val f1 = fragments[0] as PlaintextFragment
            f1.setPrivateData(importType, it.keystore)
            val f2 = fragments[1] as CodeFragment
            f2.setPrivateData(it.keystore)
        }
        viewModel.getPrivateKeyData().observe(this) {
            val f1 = fragments[0] as PlaintextFragment
            f1.setPrivateData(importType, it.private_key)
            val f2 = fragments[1] as CodeFragment
            f2.setPrivateData(it.private_key)
        }
    }

    private fun initClick() {
        dataBinding.include14.ivHeadBack.setOnClickListener {
            this.finish()
        }
    }

    private fun initTitle() {
        when (importType) {
            1 -> {
                dataBinding.include14.tvHeadTitles.text =
                    getString(R.string.impOut, getString(R.string.keyStore))
            }
            2 -> {
                dataBinding.include14.tvHeadTitles.text =
                    getString(R.string.impOut, getString(R.string.privateKey))
            }
        }

    }

    private fun initView() {
        dataBinding.easyIndicator.setTabTitles(titles)
        dataBinding.easyIndicator.setViewPager(
            dataBinding.vp,
            FragmentAdapter(supportFragmentManager, fragments)
        )
    }
}